import os
import json
import time
import base64
import xlsxwriter
from io import BytesIO
from apis import api_routes
from flask import g, request, jsonify, Response, abort
from security.decoration import certification
from models.logs.logs import Logs
from models.logs.gather import Gather
from models.facility.facility import Facility
from models.logs.images import Images
from public.local import date_type, datetime_type
from datetime import datetime, timedelta
from sqlalchemy import and_
from typing import List, Union
from urllib.parse import unquote, quote
from public.local import local_time


base_dir = "E:\MESIMAGEALL"


@api_routes.route("/images", methods=["POST"])
def func_images_post_api():
    """
    设备上传照片到MES,后端专用的, 前端无需操作
    http://127.0.0.1:8080/api/images
    Content-Type=multipart/form-data
    methods=["POST"]
    {
    }
    :return:
        {'status': 200}
    ---
    tags:
      - 采集数据模块
    """
    images0 = request.files.get("image0")
    images1 = request.files.get("image1")

    if images0 is None or images1 is None:
        abort(code=400)
    prefix0, prefix1 = "WS04AUD", "WS04ALR"

    filename = images0.filename
    data_array0 = images0.read()
    data_array1 = images1.read()

    now = datetime.now()
    base_dirs0 = base_dir + os.sep + prefix0 + os.sep + str(now.year) + os.sep + time.strftime("%Y-%m-%d")
    if not os.path.exists(base_dirs0):
        os.makedirs(base_dirs0)
    all_dirs0: str = base_dirs0 + os.sep + filename
    with open(all_dirs0, "wb") as file:
        file.write(data_array0)
    g.session.add(Images(
        time=datetime_type(),
        ft_id=10,
        sequence=filename,
        path=all_dirs0,
        isdel=False
    ))

    base_dirs1 = base_dir + os.sep + prefix1 + os.sep + str(now.year) + os.sep + time.strftime("%Y-%m-%d")
    if not os.path.exists(base_dirs1):
        os.makedirs(base_dirs1)
    all_dirs1: str = base_dirs1 + os.sep + filename
    with open(all_dirs1, "wb") as file:
        file.write(data_array1)
    g.session.add(Images(
        time=datetime_type(),
        ft_id=10,
        sequence=filename,
        path=all_dirs1,
        isdel=False
    ))
    g.session.commit()
    return jsonify({'status': 200})


@api_routes.route("/images", methods=["GET"])
def func_images_get_api():
    """
    查询工业相机上传到MES照片, 完成API开发任务
    http://127.0.0.1:8080/api/images
    Content-Type=application/x-www-form-urlencoded
    methods=["GET"]
    {
    "index"         int      ****   第几页，默认为1
    "size"          int      ****   每页数据多少, 默认每页10条数据
    "start"         string          开始时间, 默认今天时间  格式 %Y-%m-%d
    "finish"        string          结束时间，默认今天时间  格式 %Y-%m-%d
    "facility_id"   int             设备ID  http://127.0.0.1:8080/api/query/facility
    "sequence"      string          产品SN，不支持模糊查询
    }
    :return:
        {'status': 200, 'data': resp, "index": index, "size": size, "total": count, "pages": page}
    ---
    tags:
      - 采集数据模块
    """
    size = request.args.get("size", default=10, type=int)
    index = request.args.get("index", default=1, type=int)
    start = request.args.get("start", default=None, type=str)
    finish = request.args.get("finish", default=None, type=str)
    ft_id: Union[int, None] = request.args.get("facility_id", default=None, type=int)
    sequence: Union[str, None] = request.args.get("sequence", default=None, type=str)

    # arg0, arg1 = start, finish
    # if start is None:
    #     arg0 = date_type()
    # else:
    #     arg0 = datetime.strptime(start, "%Y-%m-%d")
    # if finish is None:
    #     arg1 = date_type() + timedelta(days=1) - timedelta(seconds=1)
    # else:
    #     arg1 = datetime.strptime(finish, "%Y-%m-%d") + timedelta(days=1) - timedelta(seconds=1)
    arg0, arg1 = start, finish
    if start is None or len(start) == 0:
        # arg0 = date_type()
        arg0 = None
    else:
        arg0 = datetime.strptime(start, "%Y-%m-%d")
    if finish is None or len(finish) == 0:
        # arg1 = date_type() + timedelta(days=1) - timedelta(seconds=1)
        arg1 = None
    else:
        arg1 = datetime.strptime(finish, "%Y-%m-%d") + timedelta(days=1) - timedelta(seconds=1)

    parameter: list = []
    if arg0 is not None:
        parameter.append(Images.time >= arg0)
    if arg1 is not None:
        parameter.append(Images.time <= arg1)
    if ft_id is not None:
        parameter.append(Images.ft_id == ft_id)

    if sequence is not None and len(sequence) > 0:
        if "." not in sequence:
            sequence = "{}.JPG".format(sequence)
        parameter.append(Images.sequence == sequence)

    count = g.session.query(Images.id).filter(and_(* parameter)).count()
    page: int = int((count / size) + 1) if (count / size) > int(count / size) else int(count / size)

    ftall = {}
    fts: List[Facility] = g.session.query(Facility).order_by(Facility.id).all()
    for xx in fts:
        ftall[xx.id] = xx.name

    data: List[Images] = g.session.query(Images).filter(and_(* parameter)).order_by(Images.id).offset((index - 1) * size).limit(size).all()
    resp: list = []
    for index, itr in enumerate(data):
        r_image: Union[str, None] = None
        if os.path.exists(itr.path):
            with open(itr.path, "rb") as file:
                bin_data = file.read()
            r_image = base64.b64encode(bin_data).decode('utf-8')
        resp.append({
            "image_id": itr.id,
            "time": itr.time.strftime("%Y-%m-%d %H:%M:%S"),
            "sequence": itr.sequence,
            "facility_id": itr.ft_id,
            "facility_name": ftall[itr.ft_id],
            "image": r_image,
            "path": itr.path,
        })

    doc: dict = {
        "image_id": "数据库ID",
        "time": "操作时间",
        "sequence": "产品SN",
        "facility_id": "设备ID",
        "facility_name": "设备名称",
        "image": "base64照片, 可能为空",
        "path": "磁盘保存路径"
    }
    return jsonify({'status': 200, 'data': resp, "index": index, "size": size, "total": count, "pages": page, "doc": doc})
